<script setup lang="ts">
import CdlTable from "@/components/table";
import {TableTree} from "@/interfaces/components/Table";
import {Driver} from "@/interfaces/views/vehicle/driver";
import {ref, defineEmits} from "vue";
import {
  useFleetDelDriverApi,
  useFleetInsertDriverApi,
  useGetDriverListApi,
  useGetFleetDriverApi
} from "@/api/vehicle/fleet";
import {ElButton, ElMessage} from "element-plus";
import {cloneDeep} from "lodash";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: false
  },
  query: {
    type: Function,
    required: true
  },
})
const emit = defineEmits(["close"])
init()

const tableRef = ref()
const tableData = ref([])
const tableTree: TableTree<Driver> = {
  colRule: [
    {type: "selection", width: 40},
    {ti: "关联车辆", prop: "licensePlate"},
    {ti: "关联司机", prop: "name"},
  ]
}
const tableUpdateTree: TableTree<Driver> = {
  colRule: [
    {type: "selection", width: 40, selectTable: (row, index)=>{
        return !(index === 0)
      }},
    {ti: "关联车辆", prop: "licensePlate"},
    {ti: "是否是队长", prop: "fleetCaptain", dict: "overall_yes_or_no"},
    {ti: "关联司机", prop: "name"},
  ]
}
function submit(){
  console.log("@@@@@@@@")
  let arr: any[] = cloneDeep(tableRef.value.multipleSelection)
  if(!arr.length) {
    ElMessage.warning("你未选择任何数据！")
    return
  }
  if(!props.name){
    useFleetDelDriverApi(
      arr.map(item => item.id)
    ).then(() => {
      ElMessage.success("删除成功!")
      props.query()
    })
  }else {
    useFleetInsertDriverApi({
      id: props.id,
      name: props.name,
      driverIds: arr.map(item => item.id)
    }).then(() => {
      ElMessage.success("新增成功!")
      props.query()
    })
  }
  emit("close")
}

/**
 * 初始化
 */
function init(){
  if(!props.name){
    useGetFleetDriverApi({
      id: props.id
    }).then(res =>{
      tableData.value = res.data
    })
  }else {
    useGetDriverListApi().then(res =>{
      tableData.value = res.data
    })
  }
}
</script>

<template>
  <CdlTable ref="tableRef" :template-tree="props.name? tableTree : tableUpdateTree"
            :data="tableData" border></CdlTable>
  <ElButton type="primary" style="float: right; margin-top: 15px" @click="submit">提交</ElButton>
</template>
